package tree.tree2.symmetry.isSame;

import tree.TreeNode;

/**
 * @ClassName IsSubTree
 * @Description TODO
 * @Author lenovo
 * @Date 2023-04-24 10:12
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class IsSubTree {

    /**
     * 572. 另一棵树的子树
     * 给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在，返回 true ；否则，返回 false 。
     * <p>
     * 二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
     *          1                 2             1
     *      2       3        3        4     2      3
     *
     *  3      4
     */



    public boolean isSubtree(TreeNode root, TreeNode subRoot) {

        if(isSameTree(root,subRoot)){
            return true;
        }
        if(isSubtree(root.left,subRoot)){
            return true;
        }
        if(isSubtree(root.right,subRoot)){
            return true;
        }
        return false;
    }

    private boolean isSameTree(TreeNode root, TreeNode subRoot) {
        if(root==null && subRoot!=null){
            return false;
        }
        if(root!=null && subRoot==null){
            return false;
        }
        if(root==null && subRoot==null){
            return true;
        }
        if(root.val!=subRoot.val){
            return false;
        }
        boolean leftIsSame = isSubtree(root.left,subRoot.left);
        boolean rightIsSame = isSubtree(root.right,subRoot.right);
        return leftIsSame&&rightIsSame;
    }


    public static void main(String[] args) {
        IsSubTree isSubTree = new IsSubTree();
        TreeNode p = new TreeNode(1);

        TreeNode q = new TreeNode(2);
        q.left = new TreeNode(3);
        q.right = new TreeNode(4);
        p.left = q;
        p.right = new TreeNode(3);

        System.out.println(isSubTree.isSubtree(p, q));
    }
}